package cn.yunyichina.provider.base.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.yunyichina.provider.base.service.OrgService;
import cn.yunyichina.provider.base.utils.CacheConstant;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.base.OrgSetting;
import cn.yunyichina.provider.iface.entity.base.OrgSettingVoResponse;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.utils.commons.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.common.utils.CollectionUtils;

import cn.yunyichina.provider.base.dao.RuleDao;
import cn.yunyichina.provider.base.entity.Rule;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.iface.entity.cache.SessionInfo;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.utils.convert.JsonUtils;

import javax.annotation.Resource;

/**
 * 
 * @projectName:yyt-provider-base
 * @author:yangfan
 * @description:规则配置操作
 * @date:2016年11月14日
 * @className:RuleServiceImpl
 * @pakeage:cn.yunyichina.provider.base.service.impl
 */
@Service
public class RuleServiceImpl {
	private static final Logger logger = LoggerFactory.getLogger(RuleServiceImpl.class);
	@Autowired
	private RuleDao ruleDao;

	@Resource
	private OrgService orgService;

	/**
	 * 
	 * @methodName:selectRule yyt.base.rule.select
	 * @description:获取具体医院某条规则
	 * @author:yangfan
	 * @date:2016年11月15日
	 * @param data
	 * @return:Response
	 */
	public Response selectRule(String data) {
		Response response = new Response();
		Map<String, String> map = JsonUtils.parseObject(data, Map.class);
		String attribute_name = map.get("attribute_name");
		String org_code = map.get("org_code");
        String branch_code = "";//map.get("branch_code");规则按医院查询，不细到分院
//		String platform_org_app_code = map.get("platform_org_app_code");

//		if(StringUtils.isBlank(attribute_name)){
//			response.setResultCodeAndMessage("1101", "规则名不能为空");
//			return response;
//		}
		if(StringUtils.isBlank(org_code)){
			response.setResultCodeAndMessage("1101", "org_code不能为空");
			return response;
		}

		String field = StringUtils.isNotBlank(branch_code) ? (org_code + ":" + branch_code) : org_code;
		String cacheValue = CacheService.getGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE,CacheConstant.CACHE_RULE_REGION,
				CacheConstant.CACHE_HASH_KEY,field);
		List<Rule> list;
		if(StringUtils.isNotBlank(cacheValue)){
			list = JsonUtils.parseArray(cacheValue, Rule.class);
		}else {
			//缓存查不到，从数据库中查询并更新缓存
			Rule ruleQuery = new Rule();
			ruleQuery.setOrgCode(org_code);
			if(StringUtils.isNotBlank(branch_code)){
				ruleQuery.setBranchCode(branch_code);
			}
			list = this.ruleDao.select(ruleQuery);
			if(!org.springframework.util.CollectionUtils.isEmpty(list)) {
				CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_RULE_REGION,
						CacheConstant.CACHE_HASH_KEY, field, JsonUtils.toJsonString(list));
			}
		}


		if(!CollectionUtils.isEmpty(list)){
			if(StringUtils.isBlank(attribute_name)){
				//属性名为空，返回整个医院的规则
				response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(list));
				return response;
			}
			for(Rule rule : list){
				if(attribute_name.equals(rule.getAttributeName())){
					response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(rule));
					return response;
				}
			}
		}
		logger.info("根据查询逻辑 条件:org_code:"+org_code+",branch_code:"+branch_code+",attribute_name:"+attribute_name+" 表【sys_rule】并不存在该记录!");
		response.setResultCodeAndMessageAndResult("0", "查询不到记录", null);
		return response;
	}

	/**
	 * yyt.base.rule.query
	 * @param data
	 * @return
	 */
	public Response queryRule(String data) {
		Response response = new Response();

		Rule rule = JsonUtils.parseObject(data, Rule.class);

		List<Rule> list = this.ruleDao.select(rule);

		if(!CollectionUtils.isEmpty(list)){
			response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(list));
			return response;
		}

		response.setResultCodeAndMessageAndResult("0", "查询不到记录", null);
		return response;
	}


	/**
	 * @methodName:yyt.base.rule.list.get
	 * @description:根据医院编码，规则类型来查询缓存对应的规则类型下的所有规则
	 * @author:wwb
	 * @date:2017年5月10日
	 * @param data
	 * @return:Response
	 */
	public Response getRuleList(String data){
		Response response = new Response();
		Map<String, String> map = JsonUtils.parseObject(data, Map.class);
		String attribute_type = map.get("attribute_type");
		String org_code = map.get("org_code");
		if(StringUtils.isBlank(attribute_type)){
			response.setResultCodeAndMessage("1101", "规则类型不能为空");
			return response;
		}
		if(StringUtils.isBlank(org_code)){
			response.setResultCodeAndMessage("1101", "医院id不能为空");
			return response;
		}
		Rule rule = new Rule();
		rule.setOrgCode(org_code);
		rule.setAttributeType(Short.valueOf(attribute_type));
		List<Rule> list = this.ruleDao.select(rule);
		response.setResultCodeAndMessageAndResult("0", "查询成功", JsonUtils.toJsonString(list));
		return response;
	}

	/**
	 * 
	 * @methodName:updateRules
	 * @description:具体医院某一条或者多条具体详细规则配置修改
	 * @author:yangfan
	 * @date:2016年12月14日
	 * @param data
	 * @return:Response
	 */
	@Transactional
	public Response updateRules(String data,String sessionId) {
		Response response = new Response();
		SessionInfo sessions = CacheService.getSessionInfo(sessionId);
		if (null == sessions) {
			response.setResultCodeAndMessage("1101", "用户信息为空，请先登录");
			return response;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Rule> list = JsonUtils.parseArray(data, Rule.class);
		if (list.size() == 0) {
			response.setResultCodeAndMessage("1101", "查询规则数据参数不能为空");
			return response;
		}
		for (int i = 0; i < list.size(); i++) {
			if (StringUtils.isBlank(list.get(i).getAttributeName())) {
				response.setResultCodeAndMessage("1101", "查询规则数据规则属性名不能为空");
				return response;
			}
			if(StringUtils.isBlank(list.get(i).getBranchId())){
				response.setResultCodeAndMessage("1101", "查询医院id不能为空");
				return response;
			}
			list.get(i).setUpdateBy(sessions.getUserName());
			list.get(i).setUpdateTime(sdf.format(new Date()));
		}
		try {
			this.ruleDao.batchUpdate(list);
			response.setResultCodeAndMessage("0", "修改成功");
		} catch (Exception e) {
			logger.error("修改医院规则失败",e.toString());
			response.setResultCodeAndMessage("1999", "修改医院规则失败异常");
		}
		return response;
	}

	/**
	 * 刷新规则配置缓存
	 * yyt.base.rule.cache.reload
	 * @param data
	 * @return
	 */
	public Response reloadRuleCache(String data, String sessionId) {
		Response response = new Response();
		Rule requestVo = JsonUtils.parseObject(data, Rule.class);
		if(StringUtils.isBlank(requestVo.getOrgCode())){
			response.setResultCodeAndMessage("1101", "org_code不能为空");
			return response;
		}

		Rule ruleQuery = new Rule();
		ruleQuery.setOrgCode(requestVo.getOrgCode());
		if(StringUtils.isNotBlank(requestVo.getBranchCode())){
			ruleQuery.setBranchCode(requestVo.getBranchCode());
		}
		List<Rule> ruleList = this.ruleDao.select(ruleQuery);

		if(!CollectionUtils.isEmpty(ruleList)){
			for(Rule rule:ruleList) {
				String field = StringUtils.isNotBlank(requestVo.getBranchCode()) ? (requestVo.getOrgCode() + ":" + requestVo.getBranchCode()) : requestVo.getOrgCode();
				CacheService.setGlobalKeyHash(CacheConstant.CACHE_BASE_MODULE, CacheConstant.CACHE_RULE_REGION,
						CacheConstant.CACHE_HASH_KEY, field, JsonUtils.toJsonString(ruleList));
			}
		}

		response.setResult(JsonUtils.toJsonString(ruleList));
		response.setResultCodeAndMessage("0", "更新规则缓存成功");
		return response;
	}

	/**
	 * 新增或更新一条规则
	 * yyt.base.rule.save
	 * @param data
	 * @return
	 */
	public Response saveRule(String data,String sessionId) {
		Response response = new Response();
		Rule rule = JsonUtils.parseObject(data, Rule.class);
		String attributeName = rule.getAttributeName();
		String orgCode = rule.getOrgCode();
		if(StringUtils.isBlank(orgCode)){
			response.setResultCodeAndMessage("1006","org_code不能为空");
			return response;
		}
		if(StringUtils.isBlank(attributeName)){
			response.setResultCodeAndMessage("1006","attribute_name不能为空");
			return response;
		}

		if(StringUtils.isBlank(rule.getId())){
			Rule query = new Rule();
			query.setOrgCode(orgCode);
			query.setAttributeName(attributeName);
			List<Rule> list = this.ruleDao.select(query);
			if(CollectionUtils.isEmpty(list)){
				//新增规则
				Org org = orgService.getOrgByCode(rule.getOrgCode());
				if(org == null){
					response.setResultCodeAndMessage("1006","没有对应的机构:" + rule.getOrgCode());
					return response;
				}
				rule.setId(PKGenerator.generateId());
				rule.setCreatedTime(DateUtils.dateToString(new Date()));
				rule.setOrgName(org.getOrgName());
				rule.setOrgId(org.getId());
				ruleDao.insert(rule);
			}else{
				rule.setId(list.get(0).getId());
				rule.setUpdateTime(DateUtils.dateToString(new Date()));
				ruleDao.update(rule);
			}
		}

		//更新缓存
		reloadRuleCache("{\"org_code\":\""+ orgCode +"\"}",sessionId);

		response.setResultCodeAndMessage("0","成功");
		response.setResult(JsonUtils.toJsonString(rule));
		return response;
	}

	/**
	 * 新增或更新多条规则
	 * yyt.base.rule.batch.save
	 * @param data
	 * data格式参考:{"rules":"[{\"org_code\":\"fsszyy\",\"attribute_name\":\"copyInitialDeposit\",\"attribute_properties\":\"200\"},{\"org_code\":\"fsszyy\",\"attribute_name\":\"copyMultipleCopiesAddDeposit\",\"attribute_properties\":\"50\"},{\"org_code\":\"fsszyy\",\"attribute_name\":\"copySupportMultipleCopies\",\"attribute_properties\":\"1\"},{\"org_code\":\"fsszyy\",\"attribute_name\":\"copySupportPatientSelectHISsMedicalRecords\",\"attribute_properties\":\"1\"},{\"org_code\":\"fsszyy\",\"attribute_name\":\"copyItemOptional\",\"attribute_properties\":\"{\\\"radio\\\":\\\"1\\\",\\\"items\\\":[\\\"1\\\",\\\"5\\\"]}\"},{\"org_code\":\"fsszyy\",\"attribute_name\":\"copyPayWarmTip\",\"attribute_properties\":\"7837837\"}]"}
	 * @return
	 */
	public Response saveRuleBatch(String data,String sessionId) {
		logger.info("新增或更新多条规则,data=" + data + ",sessionId=" + sessionId);
		Response response = new Response();

		List<Rule> rules = null;
		try {
			Map<String,String> vo = JsonUtils.parseObject(data,Map.class);
			String rulesData = JsonUtils.toJsonString(vo.get("rules"));
			rules = JsonUtils.parseObject(rulesData, List.class);
		} catch (Exception e) {
			e.printStackTrace();
			response.setResultCodeAndMessage("1006","数据格式错误");
			return response;
		}
		if(rules.size() == 0){
			response.setResultCodeAndMessage("1006","参数不能为空");
			return response;
		}
		for (int i = 0; i < rules.size(); i++) {
			Rule rule = JsonUtils.parseObject(JsonUtils.toJsonString( rules.get(i)),Rule.class);
			response = saveRule(JsonUtils.toJsonString(rule), sessionId);
			if(!"0".equals(response.getResultCode())){
				return response;
			}
		}
		return response;
	}
}
